package com.dpad.crmclientapp.android.modules.newapp.ui.fragment


import android.support.v4.widget.SwipeRefreshLayout
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import com.alibaba.android.arouter.launcher.ARouter
import com.bigkoo.pickerview.builder.OptionsPickerBuilder
import com.bigkoo.pickerview.listener.OnOptionsSelectListener
import com.chad.library.adapter.base.BaseQuickAdapter
import com.dpad.crmclientapp.android.modules.newapp.presenter.UserCenterPresenter
import com.dpad.crmclientapp.android.util.utils.*
import com.dpad.telematicsclientapp.adapter.UserCenterAdapter
import com.dpad.telematicsclientapp.android.R
import com.dpad.telematicsclientapp.entity.UserCenterOnclick
import com.dpad.telematicsclientapp.event.CarChangeEvent
import com.dpad.telematicsclientapp.mvp.event.BusProvider
import com.dpad.telematicsclientapp.mvp.imageloader.ILFactory
import com.dpad.telematicsclientapp.mvp.imageloader.ILoader
import com.dpad.telematicsclientapp.mvp.kit.Kits
import com.dpad.telematicsclientapp.netlibrary.AppConstants
import com.dpad.telematicsclientapp.netlibrary.Contances
import com.dpad.telematicsclientapp.netlibrary.MainApplicaton
import com.dpad.telematicsclientapp.netlibrary.base.basecopy.BaseCopyFragment
import com.dpad.telematicsclientapp.netlibrary.http.ApiConstants
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.HomeCarDataBean
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.UserCenterBean
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.UserCenterEntry
import com.dpad.telematicsclientapp.netlibrary.newapp.entity.UserCenterVo
import com.dpad.telematicsclientapp.ui.HomeActivity
import com.dpad.telematicsclientapp.util.DataStatisticsUtils
import com.dpad.telematicsclientapp.util.PreferenceUtils
import com.dpad.telematicsclientapp.util.TitleToCode
import com.dpad.telematicsclientapp.util.utils.*
import com.dpad.telematicsclientapp.utils.PopupMenuUtil
import com.dpad.telematicsclientapp.weiget.CustomLoadMoreView
import com.socks.library.KLog
import io.reactivex.android.schedulers.AndroidSchedulers
import kotlinx.android.synthetic.main.fragment_nomal_usercenter.*
import rx.subscriptions.CompositeSubscription
import java.lang.Exception
import java.util.*

/**
 * ================================================
 * 作    者：wenbody
 * 版    本：1.0
 * 创建日期：2019/12/31 16:04
 * 描    述：
 * 修订历史：
 * ================================================
 */
class UserCenterFragment : BaseCopyFragment<UserCenterPresenter>(), BaseQuickAdapter.OnItemClickListener, BaseQuickAdapter.RequestLoadMoreListener, SwipeRefreshLayout.OnRefreshListener, PopupMenuUtil.OnItemCheckedChange {
    private lateinit var userCenterAdapter: UserCenterAdapter
    var data = mutableListOf<UserCenterBean>()
    var result = mutableListOf<UserCenterVo.Result.InterfaceData.Result>()
    private lateinit var callBack: UserCenterOnclick

    private var time = "" //预约充电时间
    private var pageIndex = 1
    private var pageSize = 20
    private var firstIndex = 0
    //是否是刷新 默认进来是刷新 true
    private var isRefresh = true
    private var ntspAppUserinfo: UserCenterVo.Result.NtspAppUserinfo? = null

    private var vehinfosBeans: ArrayList<HomeCarDataBean.ResultBean.VehinfosBean>? = null

    private var startDateTime = ""
    private var endDateTime = ""

    private var cityCode: String = ""
    private var lng: String = ""
    private var lat: String = ""
    private var needLoadImage = false

    override fun initPageData() {

        userCenterRv.layoutManager = LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false)
        userCenterAdapter = UserCenterAdapter(context, data)
        userCenterRv.adapter = userCenterAdapter
        userCenterAdapter.bindToRecyclerView(userCenterRv)
        userCenterAdapter.onItemClickListener = this
//        userCenterAdapter.setOnLoadMoreListener(this)
        userCenterAdapter.setOnLoadMoreListener(this, userCenterRv)
        userCenterAdapter.setLoadMoreView(CustomLoadMoreView())
        callBack = context as HomeActivity
        userCenterSrl.setColorSchemeResources(R.color.colorPrimary)
        userCenterSrl.setOnRefreshListener(this)
        userEmptyIm.setImageResource(if (Kits.Empty.check(MainApplicaton.userVehType) || MainApplicaton.userVehType == "0") R.mipmap.customer_bg else R.mipmap.usercenter_empty_im)



        changFragment.setOnClickListener {
            DataStatisticsUtils.addData(DataStatisticsUtils.getDatasBean("", TitleToCode.TYPE171.title, System.currentTimeMillis().toString(), Constant.NOMAL))
            callBack.changeUserCenter(true)
        }
        selectDate.setOnClickListener {
            showMouttDialog()
        }
        selectCar.setOnClickListener {
            vehinfosBeans?.let { it1 -> showCarList(it1) }
        }
        userIcon.setOnClickListener {
            if (ntspAppUserinfo != null) {
//                val intent = Intent(context, UserDocumentActivity::class.java)
//                intent.putExtra(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
//                startActivity(intent)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_USERDOCUMENT, Contances.GROUP_OTHER)
                        .withObject(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
                        .navigation(context)

            }
        }
        userNickName.setOnClickListener {
            if (ntspAppUserinfo != null) {
//                val intent = Intent(context, UserDocumentActivity::class.java)
//                intent.putExtra(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
//                startActivity(intent)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_USERDOCUMENT, Contances.GROUP_OTHER)
                        .withObject(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
                        .navigation(context)


            }
        }
        userTag.setOnClickListener {
            if (ntspAppUserinfo != null) {
//                val intent = Intent(context, UserDocumentActivity::class.java)
//                intent.putExtra(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
//                startActivity(intent)

                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_USERDOCUMENT, Contances.GROUP_OTHER)
                        .withObject(START_USER_DOC_ACTIVITY_KEY, ntspAppUserinfo)
                        .navigation(context)


            }
        }
        userEmptyIm.setOnClickListener {
            if (MainApplicaton.userVehType == "0") {//游客,跳转到试驾
                cityCode = PreferenceUtils.getInstance(context).getString("cityCode")
                lng = PreferenceUtils.getInstance(context).getString("longitude")
                lat = PreferenceUtils.getInstance(context).getString("latitude")
                val url = ApiConstants.getAppYysjUrl() +
                        "&cityCode=" + cityCode +
                        "&lng=" + lng +
                        "&lat=" + lat +
                        "&carTypeCode=default"+
                        "&brandCode=" + AppConstants.BRANDCODE
//                val intent = Intent(context, NewWebViewActivity::class.java)
//                intent.putExtra(Constant.WEBVIEWKEY, url)
//                intent.putExtra(Constant.WEBVIEW_TITLE_KEY, "预约试驾")
//                context.startActivity(intent)


                ARouter.getInstance()
                        .build(Contances.URL_ACTIVITY_NEWWEBVIEW, Contances.GROUP_OTHER)
                        .withString(Constant.WEBVIEWKEY, url)
                        .withString(Constant.WEBVIEW_TITLE_KEY, "预约试驾")
                        .navigation(context)

            }
        }

        BusProvider.getBus().toFlowable(CarChangeEvent::class.java).observeOn(AndroidSchedulers.mainThread()) //观察的对象
                .subscribe { t ->
                    if (t != null) {
                        startDateTime = ""
                        endDateTime = ""
                        try {
                            selectDate?.text = "全部"
                        } catch (e: Exception) {

                        }

                        //                            onRefresh()
                    }
                }


        loadPIc()
    }

    override fun useEventBus(): Boolean {
        return true
    }

    override fun getLayout(): Int {
        return R.layout.fragment_nomal_usercenter
    }

    override fun newPresenter(subscriptions: CompositeSubscription?): UserCenterPresenter {
        return UserCenterPresenter()
    }

    override fun onItemClick(adapter: BaseQuickAdapter<*, *>?, view: View?, position: Int) {

        if (data[position].clickAble) {
            when (data[position].data.eventType) {
                 "appointment_add", "appointment_update" -> {//完成保养
//                    val intent = Intent(activity, BookingDetailActivity2::class.java)
//                    intent.putExtra("BespeakInfoHistoryVO", data[position].data.eventDetailId)
//                    startActivity(intent)


                     ARouter.getInstance()
                             .build(Contances.URL_ACTIVITY_BOOKINGDETAIL, Contances.GROUP_YUYUE)
                             .withString("BespeakInfoHistoryVO", data[position].data.eventDetailId)
                             .navigation(context)



                }
                "rescues_update", "rescues_add" -> {//增加救援
//                    val intent = Intent(activity, JyDetailActivity::class.java)
//                    intent.putExtra("id", data[position].data.eventDetailId)
//                    startActivity(intent)


                    ARouter.getInstance()
                            .build(Contances.URL_ACTIVITY_JYDETAIL, Contances.GROUP_JIUYUAN)
                            .withString("id", data[position].data.eventDetailId)
                            .navigation(context)



                }
                "mall_order" -> {
//                    cityCode = PreferenceUtils.getInstance(context).getString("cityCode")
//                    lng = PreferenceUtils.getInstance(context).getString("longitude")
//                    lat = PreferenceUtils.getInstance(context).getString("latitude")
                    if (Kits.Empty.check(data[position].data.eventDetailId) || !data[position].data.eventDetailId.contains("http")) {
                        T.showToastSafeError("数据异常")
                        return
                    }

                    val url = data[position].data.eventDetailId +
                            "&token=" + MainApplicaton.LOGINRESULTVO.token +
                            "&vin=" + MainApplicaton.vin +
                            "&userId=" + MainApplicaton.LOGINRESULTVO.userId +
//                            "&cityCode=" + cityCode +
//                            "&lng=" + lng +
//                            "&lat=" + lat +
                            "&flag=1" +
                            "&phone=" + MainApplicaton.LOGINRESULTVO.userName +
                            "&brandCode=" + AppConstants.BRANDCODE
//                    val intent = Intent(context, NewWebViewActivity::class.java)
//                    intent.putExtra(Constant.WEBVIEWKEY, url)
//                    intent.putExtra(Constant.WEBVIEW_TITLE_KEY, "我的订单")
//                    context.startActivity(intent)

                    ARouter.getInstance()
                            .build(Contances.URL_ACTIVITY_NEWWEBVIEW, Contances.GROUP_OTHER)
                            .withString(Constant.WEBVIEWKEY, url)
                            .withString(Constant.WEBVIEW_TITLE_KEY, "我的订单")
                            .navigation(context)


                }
//                "rescues_add" -> {//取消救援
//                    val intent = Intent(activity, JyDetailActivity::class.java)
//                    intent.putExtra("id", data[position].data.eventDetailId)
//                    startActivity(intent)
//                }
//                "appointment_add" -> {//增加预约
//                    val intent = Intent(activity, BookingDetailActivity2::class.java)
//                    intent.putExtra("BespeakInfoHistoryVO", data[position].data.eventDetailId)
//                    startActivity(intent)
//                }
//                "appointment_update" -> {//取消预约
//                    val intent = Intent(activity, BookingDetailActivity2::class.java)
//                    intent.putExtra("BespeakInfoHistoryVO", data[position].data.eventDetailId)
//                    startActivity(intent)
//                }
            }
        }
    }


    //选择预约充电时间
    private fun showMouttDialog() {
        val selectedDate = Calendar.getInstance()
        val list1 = arrayListOf<String>()
        val list2 = arrayListOf<ArrayList<String>>()
        val list = arrayListOf("全部")
        val listSecond = arrayListOf("1月", "2月", "3月", "4月", "5月", "6月", "7月", "8月", "9月", "10月", "11月", "12月")
        list1.add("全部")
        val calendar = Calendar.getInstance()
        val year = calendar[Calendar.YEAR].toString()
        val month = calendar[Calendar.MONTH]
        for (item in selectedDate.get(Calendar.YEAR) downTo selectedDate.get(Calendar.YEAR) - 5) {
            list1.add(item.toString())
        }
        for (index in list1.indices) {
            if (index == 0) {
                list2.add(list)
            } else {
                list2.add(listSecond)
            }

        }
        val timePicker = OptionsPickerBuilder(context, OnOptionsSelectListener { options1, options2, options3, v ->
            if (options1 == 0) {
                startDateTime = ""
                endDateTime = ""
                selectDate.text = "全部"
            } else {
                if (year == list1[options1]) {
                    if (options2 > month) {
                        T.showToastSafeError("请选择正确的日期")
                        return@OnOptionsSelectListener
                    }
                }
                val selectTime = "${list1[options1]}/${(if (options2 < 9) "0${options2 + 1}" else (options2 + 1).toString())}"
                startDateTime = "${list1[options1]}-${(if (options2 < 9) "0${options2 + 1}" else (options2 + 1).toString())}-01 00:00:00"
                endDateTime = "${list1[options1]}-${(if (options2 < 9) "0${options2 + 1}" else (options2 + 1).toString())}-${DateUtil.getDateLastDay(list1[options1], (options2).toString())} 23:59:59"
                selectDate.text = selectTime
            }
            onRefresh()
        }).setCancelText("取消")//取消按钮文字
                .setSubmitText("确认")//确认按钮文字
                .setContentTextSize(18)//滚轮文字大小
                .setTitleSize(20)//标题文字大小
                .setTitleText("选择查看周期")//标题文字
                .setOutSideCancelable(false)//点击屏幕，点在控件外部范围时，是否取消显示
                .setTitleColor(context.resources.getColor(R.color.white))//标题文字颜色
                .setSubmitColor(context.resources.getColor(R.color.colorPrimary))//确定按钮文字颜色
                .setCancelColor(context.resources.getColor(R.color.white))//取消按钮文字颜色
                .setTitleBgColor(context.resources.getColor(R.color.color_1E242C))//标题背景颜色
                .setBgColor(context.resources.getColor(R.color.color_1E242C))//滚轮背景颜色
                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .setTextColorCenter(context.resources.getColor(R.color.white))
                .setTextColorOut(context.resources.getColor(R.color.color_AEAEAE))
                .isDialog(false)//是否显示为对话框样式
                .setDividerColor(context.resources.getColor(R.color.colorPrimary))

                .build<Any>()


        timePicker.setPicker(list1 as List<String>, list2 as List<List<String>>)
        timePicker.show()
    }

    /**
     * 请求接口成功后返回数据
     */
    fun showData(value: UserCenterVo) {
        if (isRefresh) {
            moonAndSunView.startAnimator(DateUtil.isNight())
        }
        ntspAppUserinfo = value.result.ntspAppUserinfo
        value.result.ntspAppUserinfo?.let { saveToSp(it) }

        if (value.result.appFavoriteRsDtos != null && value.result.appFavoriteRsDtos!!.isNotEmpty()) {
            selectCar.visibility = View.VISIBLE
            selectCar.text = getCarNameByVin(MainApplicaton.vin, value.result.appFavoriteRsDtos)
            if (vehinfosBeans == null) {
                vehinfosBeans = arrayListOf()
            } else {
                vehinfosBeans!!.clear()
            }
            for (item in value.result.appFavoriteRsDtos!!) {
                val vehinfosBean = HomeCarDataBean.ResultBean.VehinfosBean()
                vehinfosBean.vin = item.vin
                vehinfosBean.plateNumber = item.plateNumber
                vehinfosBean.isChecked = item.vin == MainApplicaton.vin
                vehinfosBean.userVehType = if (item.userVehType.isNullOrEmpty()) "" else item.userVehType
                vehinfosBean.saleSubmodelId = item.saleSubmodelId
                vehinfosBean.settState(item.tState)
                vehinfosBeans!!.add(vehinfosBean)
            }
        } else {
            selectCar.visibility = View.GONE
            selectCar.text = "选择爱车"
        }

        userNickName.text = if (!Kits.Empty.check(value.result.ntspAppUserinfo?.nickName)) value.result.ntspAppUserinfo?.nickName else value.result.ntspAppUserinfo?.loginName

        val options = ILoader.Options(R.mipmap.default_user_im, R.mipmap.default_user_im)
        if (!Kits.Empty.check(ntspAppUserinfo?.picUrl)) {
            KLog.e("picUrl", ntspAppUserinfo!!.picUrl)
            ILFactory.getLoader().loadNet(userIcon, ntspAppUserinfo!!.picUrl, options)
        } else {
            ILFactory.getLoader().loadResource(userIcon, R.mipmap.default_user_im, null)
        }
        userTag.text = if (!Kits.Empty.check(value.result.ntspAppUserinfo?.label)) value.result.ntspAppUserinfo?.label.toString() else "编辑标签"

        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_TAG, if (!Kits.Empty.check(value.result.ntspAppUserinfo?.label)) value.result.ntspAppUserinfo?.label.toString() else "")

        userEmptyIm.setImageResource(if (Kits.Empty.check(MainApplicaton.userVehType) || MainApplicaton.userVehType == "0") R.mipmap.customer_bg else R.mipmap.usercenter_empty_im)
        /**
         * 如果是刷新并且请求数据成功,需要清除数据
         */
        if (isRefresh) {
            result.clear()
            data.clear()
            userCenterAdapter.notifyDataSetChanged()
        }
        if (value.result.interfaceData?.result != null && value.result.interfaceData!!.result.isNotEmpty()) {
            result.addAll(value.result.interfaceData!!.result)
            if (!isRefresh) {//如果是加载更多,并且有数据,需要清空数据重新计算
                data.clear()
                userCenterAdapter.notifyDataSetChanged()
            }
            /**
             * 重新处理数据
             */
            dealData(result)
            if (data.size >= 5) {
                userEmptyIm.visibility = View.INVISIBLE
            } else {
                userEmptyIm.visibility = View.VISIBLE
            }
            onloadSucceed()
            if (!isRefresh) {
                userCenterAdapter.loadMoreComplete()
            } else {
                userCenterAdapter.setEnableLoadMore(true)
            }
            userCenterAdapter.disableLoadMoreIfNotFullPage()
        } else {
            if (!isRefresh) {//说明是加载更多
                userEmptyIm.visibility = View.INVISIBLE
                userCenterAdapter.loadMoreEnd()
            } else {
                userEmptyIm.visibility = View.VISIBLE
            }
        }
    }


    fun loadPIc() {
        needLoadImage = false
        if (!Kits.Empty.check(MainApplicaton.urlMap["uservehicle"])) {
            ILFactory.getLoader().loadNet(userCenterCar, MainApplicaton.urlMap["uservehicle"], ImgUtil.getOptions(0, R.mipmap.user_center_little_car))
        }else{
            userCenterCar.setImageResource(R.mipmap.user_center_little_car)
        }
    }


    private fun dealData(value: MutableList<UserCenterVo.Result.InterfaceData.Result>) {
        for (index in value.indices) {
            val item = value[index]
            item.eventTime = getEventTime(item.eventTime)
            val clickAble = item.eventType == "maintenance_records"
                    || item.eventType == "rescues_update"
                    || item.eventType == "rescues_add"
                    || item.eventType == "appointment_add"
                    || item.eventType == "appointment_update"
                    || item.eventType == "mall_order"
            if (index == 0) {//第一项
                data.add(UserCenterBean(itemTop, item, false))
                if (value.size == 1) {
                    data.add(UserCenterBean(itemBottom, item, clickAble))
                } else {
                    if (getEventTime(item.eventTime) == getEventTime(value[index + 1].eventTime)) {
                        data.add(UserCenterBean(itemMiddle, item, clickAble))
                    } else {
                        data.add(UserCenterBean(itemBottom, item, clickAble))
                    }
                }

            } else if (index == value.size - 1) {//最后一项
                if (getEventTime(item.eventTime) == getEventTime(value[index - 1].eventTime)) {
                    data.add(UserCenterBean(itemBottom, item, clickAble))
                } else {
                    data.add(UserCenterBean(itemTop, item, false))
                    data.add(UserCenterBean(itemBottom, item, clickAble))
                }
            } else {
                if (getEventTime(item.eventTime) == getEventTime(value[index - 1].eventTime)) {//如果跟上一个一样,说明是中间或者底部
                    if (getEventTime(item.eventTime) == getEventTime(value[index + 1].eventTime)) {//如果跟后一个一样 说明是中间
                        data.add(UserCenterBean(itemMiddle, item, clickAble))
                    } else {
                        data.add(UserCenterBean(itemBottom, item, clickAble))
                    }
                } else {//跟前一个不一样 说明是重新开始
                    data.add(UserCenterBean(itemTop, item, false))
                    if (getEventTime(item.eventTime) == getEventTime(value[index + 1].eventTime)) {//如果跟后一个一样 说明是中间
                        data.add(UserCenterBean(itemMiddle, item, clickAble))
                    } else {
                        data.add(UserCenterBean(itemBottom, item, clickAble))
                    }
                }
            }
        }
        userCenterAdapter.notifyDataSetChanged()
    }

    private fun getEventTime(time: String): String {
        if (Kits.Empty.check(time)) {
            return ""
        } else {
            if (time.length >= 10) {
                return time.substring(0, 10)
            } else {
                return time
            }
        }
    }


    /**
     * 加载数据
     */
    fun loadData(isRefresh: Boolean, needLoadImage: Boolean) {
        val sortedMap: SortedMap<String, Any> = sortedMapOf(
                Pair("currentPage", pageIndex),
                Pair("pageSize", pageSize),
                Pair("data", UserCenterEntry(endDateTime, startDateTime, MainApplicaton.userVehType, MainApplicaton.vin)))
        p.getUserCenterData(sortedMap, isRefresh, needLoadImage)
    }

//    override fun getPageTitle(): String {
//        return "个人中心"
//    }

    override fun onLoadMoreRequested() {
        isRefresh = false
        pageIndex++
        loadData(isRefresh, false)
    }

    override fun onRefresh() {
        pageIndex = 1
        firstIndex = 0
        isRefresh = true
        loadData(isRefresh, needLoadImage)
    }

    override fun loading(text: String?) {
        userCenterSrl.isRefreshing = true
    }

    override fun loadingComplete() {
        super.loadingComplete()
        userCenterSrl.isRefreshing = false
//        if (!isRefresh) {
//            userCenterAdapter.loadMoreComplete()
//        }
    }

    override fun visiableLoadData() {
        initFloatButton()
        needLoadImage = false
        if (MainApplicaton.sIsLogin) {
            loadPIc()
            onRefresh()
        }
    }

    private fun initFloatButton() {
        val y: Float = if (Kits.Empty.check(PreferenceUtils.getInstance(context).getString(FLOATBUTTON_POSITION_KEY))) UIUtils.dip2px(getResources().getDimension(R.dimen.dimen_value_dp150)).toFloat() else PreferenceUtils.getInstance(context).getString(FLOATBUTTON_POSITION_KEY).toFloat()
        val isAlign = PreferenceUtils.getInstance(context).getString(FLOATBUTTON_IS_ALIGN_LEFT_KEY)
        changFragment.setLocation(isAlign, y)
    }

    private fun onloadSucceed() {
        firstIndex += pageSize
    }

    fun loadMoreFail() {
        //loadmore 失败
        userCenterAdapter.loadMoreFail()
    }

    private fun saveToSp(ntspAppUserinfo: UserCenterVo.Result.NtspAppUserinfo) {
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_REALNAME, ntspAppUserinfo.realName)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PHONE, ntspAppUserinfo.phone)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_NICKNAME, ntspAppUserinfo.nickName)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_SEX, ntspAppUserinfo.sex)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_BIRTHDAY, ntspAppUserinfo.birthday)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PIC_URL, ntspAppUserinfo.picUrl)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_PROVINCE, ntspAppUserinfo.province)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_CITY, ntspAppUserinfo.city)
        PreferenceUtils.getInstance(context).setString(Constant.USERINFO_ADDRESS, ntspAppUserinfo.address)
    }


    /**
     * 根据vin选择爱车名称
     */
    private fun getCarNameByVin(vin: String, appFavoriteRsDtos: List<UserCenterVo.Result.AppFavoriteRsDto>?): String {
        var name = ""
        if (appFavoriteRsDtos != null && appFavoriteRsDtos.isNotEmpty()) {
            for (item in appFavoriteRsDtos) {
                if (vin == item.vin) {
//                    if (Kits.Empty.check(item.pic)) {
//                        userCenterCar.setImageResource(R.mipmap.xzcx_little1)
//                    } else {
//                        ILFactory.getLoader().loadNet(userCenterCar, item.pic, ImgUtil.getOptions(R.mipmap.xzcx_little1, R.mipmap.xzcx_little1))
//                    }

                    if (!Kits.Empty.check(item.plateNumber)) {
                        name = item.plateNumber!!
                        return name
                    } else {
                        name = vin
                    }
                }
            }
        }
        return name
    }

    //弹出选择爱车的列表
    private fun showCarList(vehinfosBeans: List<HomeCarDataBean.ResultBean.VehinfosBean?>) {
        if (!Kits.Empty.check(vehinfosBeans) && vehinfosBeans.size > 0) {
            for (i in vehinfosBeans.indices) {
                vehinfosBeans[i]!!.isChecked = MainApplicaton.vin == vehinfosBeans[i]!!.vin
            }
            PopupMenuUtil.getInstance().top_show(context, normalUserCenterPartent, vehinfosBeans, this)
        } else {
            T.showToastSafeError("未获取到车辆信息")
        }
    }

    override fun OnItemCheckedLister(index: Int) {
        if (vehinfosBeans != null) {
            needLoadImage = true
            if (checkTstatus(vehinfosBeans, index)) {
                DialogUtil.showBasicDialog(context, "", "车辆未激活", "取消", "去激活") { dialog, confirm ->
                    if (confirm) {
//                        val intent = Intent(context, TChooseCarActivity3::class.java)
//                        intent.putExtra("type", "1")
//                        startActivity(intent)

                        ARouter.getInstance()
                                .build(Contances.URL_ACTIVITY_TChooseCar, Contances.GROUP_MYCAR)
                                .withString("type", "1")
                                .navigation(context)

                    }
                    dialog.dismiss()
                }
            } else {
                MainApplicaton.vin = vehinfosBeans!![index].vin
                MainApplicaton.setSaleSubmodelId(vehinfosBeans!![index].saleSubmodelId)
                MainApplicaton.userVehType = vehinfosBeans!![index].userVehType
                if (!Kits.Empty.check(vehinfosBeans!![index].plateNumber)) {
                    MainApplicaton.setPlateNumber(vehinfosBeans!![index].plateNumber)
                } else {
                    MainApplicaton.setPlateNumber("")
                }
                selectDate.text = "全部"
                startDateTime = ""
                endDateTime = ""
                needLoadImage = true
                BusProvider.getBus().post(CarChangeEvent(0, checkTstatus(vehinfosBeans, index)))
                val userLoginStateChangeEvent = UserLoginStateChangeEvent(MainApplicaton.sIsLogin, MainApplicaton.isTcar)
                BusProvider.getBus().post(userLoginStateChangeEvent)
                onRefresh()
            }
        }
    }

    /**
     * 确定当前爱车是否是未激活t车,未激活t车需要弹框
     */
    private fun checkTstatus(vehinfosBeans: ArrayList<HomeCarDataBean.ResultBean.VehinfosBean>?, index: Int): Boolean {
        if (vehinfosBeans == null || vehinfosBeans.isEmpty()) {
            return false
        } else {
            /**
             *  tState ，0:非T车辆，1:T车辆（已激活） ,  2:T车辆（未激活）
             */
            if (!Kits.Empty.check(vehinfosBeans[index].gettState()) && vehinfosBeans[index].gettState() == "2") {
                return true
            }
            return false
        }
    }
//    override fun onCreateAnimator(transit: Int, enter: Boolean, nextAnim: Int): Animator ?{
//        if (nextAnim != 0) {
//            val anim = AnimatorInflater.loadAnimator(context, nextAnim)
//            anim.addListener(object : AnimatorListenerAdapter() {
//                override fun onAnimationEnd(animation: Animator?) {
//                    super.onAnimationEnd(animation)
//                    initFloatButton()
//                    onRefresh()
//                }
//
//            })
//            return anim
//        }
//        return null
//    }

    override fun isTFragment(): Boolean {
        return true
    }

    override fun getPageTitle(): String {
        return TitleToCode.TYPE93.title
    }
}